package com.jugheadzhou.listener;

import com.jugheadzhou.core.Base;
import com.jugheadzhou.core.zk.helper.MythServiceRegistryHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author jugheadzhou
 * @date 2022-04-10
 */
@Slf4j
@SpringBootApplication
@ComponentScan(basePackages = {Base.BASE_PACKAGE})
public class ZkListenerApplication {
    @Resource
    private MythServiceRegistryHelper mythServiceRegistryHelper;

    public static void main(String[] args) {
        SpringApplication.run(ZkListenerApplication.class);
    }

    @PostConstruct
    public void init() throws Exception {
        mythServiceRegistryHelper.watchAllServiceInstances((curatorFramework, treeCacheEvent) -> {
            TreeCacheEvent.Type type = treeCacheEvent.getType();
            ChildData data = treeCacheEvent.getData();
            switch (type){
                case NODE_ADDED:
                    log.info("子节点增加, path={}, data={}",
                            data.getPath(), new String(data.getData(), StandardCharsets.UTF_8));
                    break;
                case NODE_REMOVED:
                    log.info("子节点删除, path={}, data={}",
                            data.getPath(), new String(data.getData(), StandardCharsets.UTF_8));
                    break;
                case NODE_UPDATED:
                    log.info("子节点更新, path={}, data={}",
                            data.getPath(), new String(data.getData(), StandardCharsets.UTF_8));
                    break;
                default:
                    break;
            }
        });
    }

}
